package git.soulbgm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import git.soulbgm.common.enums.Status;
import git.soulbgm.mapper.DictDataMapper;
import git.soulbgm.pojo.DictData;
import git.soulbgm.service.DictDataService;
import git.soulbgm.utils.CacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.support.SimpleValueWrapper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 字段数据服务实现类
 *
 * @author SoulBGM
 * @date 2022/03/25 16:53
 */
@Service("dict")
public class DictDataServiceImpl extends ServiceImpl<DictDataMapper, DictData> implements DictDataService {

    @Autowired
    private CacheUtil cacheUtil;

    /**
     * 缓存名称 字典
     */
    private static final String CACHE_NAME_DICT = "dict";

    /**
     * 获得类型相关的字典数据
     *
     * @param dictType 字典类型
     * @return {@link List}<{@link DictData}>
     */
    @Override
    public List<DictData> getType(String dictType) {
        SimpleValueWrapper wrapper = (SimpleValueWrapper) cacheUtil.get(CACHE_NAME_DICT, dictType);
        List<DictData> cacheList = wrapper != null ? (List<DictData>) wrapper.get() : null;
        if (cacheList == null) {
            cacheList = list(new LambdaQueryWrapper<DictData>().eq(DictData::getStatus, Status.NORMAL.code).eq(DictData::getDictType, dictType));
            cacheUtil.put(CACHE_NAME_DICT, dictType, cacheList);
        }
        return cacheList;
    }

    @Override
    public void refreshCache() {
        List<DictData> list = list();
        Map<String, List<DictData>> listMap = list.stream().collect(Collectors.groupingBy(DictData::getDictType));
        cacheUtil.removeAll(CACHE_NAME_DICT);
        Set<String> keySet = listMap.keySet();
        for (String dictType : keySet) {
            cacheUtil.put(CACHE_NAME_DICT, dictType, listMap.get(dictType));
        }
    }

}
